package com.cq.hd.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cq.hd.common.constant.MsgConstant;
import com.cq.hd.common.entity.mq.NotifyMsgSendDto;
import com.cq.hd.common.enums.biz.*;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.common.response.Throw;
import com.cq.hd.common.utils.BeanUtils;
import com.cq.hd.common.utils.StringUtils;
import com.cq.hd.member.api.TbBusinessMerchantApi;
import com.cq.hd.member.api.TbMerchantApi;
import com.cq.hd.member.api.vo.MasterBusinessVo;
import com.cq.hd.member.api.vo.MerchantPageVo;
import com.cq.hd.member.api.vo.MerchantVo;
import com.cq.hd.order.api.TbOrderApi;
import com.cq.hd.order.api.TbOrderItemApi;
import com.cq.hd.order.api.dto.OrderItemDto;
import com.cq.hd.order.api.vo.OrderItemVo;
import com.cq.hd.product.api.dto.*;
import com.cq.hd.product.api.vo.GoodsActivePageVo;
import com.cq.hd.product.api.vo.GoodsCountVo;
import com.cq.hd.product.api.vo.GoodsPageVo;
import com.cq.hd.product.mapper.TbActiveGoodsStockMapper;
import com.cq.hd.product.mq.NotifyMsgProvider;
import com.cq.hd.product.po.TbActiveGoodsStockPo;
import com.cq.hd.product.po.TbGoodsPo;
import com.cq.hd.product.mapper.TbGoodsMapper;
import com.cq.hd.product.service.TbGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author mYunYu
 * @since 2023-11-23
 */
@Service
public class TbGoodsServiceImpl extends ServiceImpl<TbGoodsMapper, TbGoodsPo> implements TbGoodsService {

    @Autowired
    private TbActiveGoodsStockMapper activeGoodsStockMapper;

    @Autowired
    private TbOrderItemApi orderItemApi;

    @Autowired
    private NotifyMsgProvider notifyMsgProvider;

    @Autowired
    private TbOrderApi orderApi;

    @Autowired
    private TbBusinessMerchantApi businessMerchantApi;

    @Autowired
    private TbMerchantApi merchantApi;

    @Override
    public Page<GoodsPageVo> pageGoods(GoodsPageDto goodsPageDto) {
        PageHelper.startPage(goodsPageDto.getPageNum(), goodsPageDto.getPageSize());
        List<GoodsPageVo> goodsPageVos = baseMapper.listGoodsByDto(goodsPageDto);
        if (!CollectionUtils.isEmpty(goodsPageVos)) {
            List<Long> goodsIds = goodsPageVos.stream().map(GoodsPageVo::getId).collect(Collectors.toList());

            Map<Long, List<TbActiveGoodsStockPo>> activeGoodsStockMap = new HashMap<>();
            // 查询冻结库存并返回，查询tb_active_goods_stock表
            List<TbActiveGoodsStockPo> tbActiveGoodsStockPos = activeGoodsStockMapper.selectList(new QueryWrapper<TbActiveGoodsStockPo>().eq("del_state", 0)
                    .in("goods_id", goodsIds));
            if (!CollectionUtils.isEmpty(tbActiveGoodsStockPos)) {
                activeGoodsStockMap = tbActiveGoodsStockPos.stream().collect(Collectors.groupingBy(TbActiveGoodsStockPo::getGoodsId));
            }

            Map<String, List<OrderItemVo>> orderItemMap = new HashMap<>();
            // 根据goodsId批量查询订单项列表
            OrderItemDto orderItemDto = new OrderItemDto();
            orderItemDto.setMulState(MulStateEnum.NO.getValue());
            orderItemDto.setGoodsIds(goodsIds);
            orderItemDto.setSubOrderStates(Arrays.asList(SubOrderStateEnum.WAIT_VERIFY.getValue(), SubOrderStateEnum.VERIFIED.getValue()));
            List<OrderItemVo> orderItemVos = orderItemApi.listByDto(orderItemDto).unpack();
            if (!CollectionUtils.isEmpty(orderItemVos)) {
                orderItemMap = orderItemVos.stream().collect(Collectors.groupingBy(OrderItemVo::getGoodsId));
            }

            List<Long> merchantIds = goodsPageVos.stream()
                    .map(GoodsPageVo::getMerchantId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            Map<Long, String> merchantNameMap = getMerchantShortNameMap(merchantIds);

            List<Long> businessMerchantIds = goodsPageVos.stream()
                    .map(GoodsPageVo::getBusinessMerchantId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            Map<Long, String> masterBusinessNameMap = getMasterBusinessNameMap(businessMerchantIds);

            for (GoodsPageVo goodsPageVo : goodsPageVos) {
                Long id = goodsPageVo.getId();
                List<TbActiveGoodsStockPo> tbActiveGoodsStockPoList = activeGoodsStockMap.get(id);
                if (!CollectionUtils.isEmpty(tbActiveGoodsStockPoList)) {
                    goodsPageVo.setFreezeStock(tbActiveGoodsStockPoList.stream().mapToInt(TbActiveGoodsStockPo::getFreezeStock).sum());
                }

                List<OrderItemVo> orderItemVoList = orderItemMap.get(String.valueOf(id));
                if (!CollectionUtils.isEmpty(orderItemVoList)) {
                    goodsPageVo.setSaleCount(orderItemVoList.size());
                }

                // 设置商户名称
                String merchantShortName = merchantNameMap.getOrDefault(goodsPageVo.getMerchantId(), "");
                goodsPageVo.setMerchantShortName(merchantShortName);

                // 设置商家名称（有些商品是策划人直接设置）
                String businessName = masterBusinessNameMap.getOrDefault(goodsPageVo.getBusinessMerchantId(), "");
                goodsPageVo.setBusinessName(businessName);
            }
        }

        PageInfo<GoodsPageVo> pageInfo = new PageInfo<>(goodsPageVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    private Map<Long, String> getMerchantShortNameMap(List<Long> merchantIds) {
        if (CollectionUtils.isEmpty(merchantIds)) {
            Collections.emptyMap();
        }
        List<String> ids = merchantIds.stream().map(String::valueOf).collect(Collectors.toList());
        List<MerchantPageVo> merchantList = merchantApi.listByIds(ids).unpack();
        return merchantList.stream()
                .collect(Collectors.toMap(MerchantPageVo::getId, MerchantPageVo::getMerchantShortName));
    }

    private Map<Long, String> getMasterBusinessNameMap(List<Long> merchantIds) {
        if (CollectionUtils.isEmpty(merchantIds)) {
            return Collections.emptyMap();
        }
        List<MasterBusinessVo> businessList = businessMerchantApi.listMasterBusinessByMerchantIds(merchantIds).unpack();
        if (CollectionUtils.isEmpty(businessList)) {
            return Collections.emptyMap();
        }
        return businessList.stream()
                .collect(Collectors.toMap(MasterBusinessVo::getMerchantId, MasterBusinessVo::getBusinessName, (k1, k2) -> k1));
    }

    @Override
    public Integer releaseGoods(GoodsReleaseDto goodsReleaseDto) {
        Integer goodsState = goodsReleaseDto.getGoodsState();
        if (goodsState == null) {
            goodsState = GoodsStateEnum.WAIT.getValue();
        }

        if (GoodsStateEnum.typeOf(goodsState) == null) {
            Throw.isBusinessException("商品状态值错误");
        }

        String goodsName = goodsReleaseDto.getGoodsName();
        BigDecimal goodsPrice = goodsReleaseDto.getGoodsPrice();
        BigDecimal originPrice = goodsReleaseDto.getOriginPrice();
        Integer totalStock = goodsReleaseDto.getTotalStock();

        // 如果是待发布(草稿箱) 类型，如果为空则不限制，如果不为空则限制
        if (!GoodsStateEnum.WAIT.getValue().equals(goodsState)) {
            if (StringUtils.isBlank(goodsName)) {
                Throw.isBusinessException("请输入商品标题");
            }

            if (goodsName.length() > 50) {
                Throw.isBusinessException("商品标题最多输入50个字");
            }

            if (goodsPrice == null) {
                goodsReleaseDto.setGoodsPrice(BigDecimal.ZERO);
//                Throw.isBusinessException("商品售价必须大于0元");
            }

            if (goodsPrice.compareTo(new BigDecimal("99999999")) > 0) {
                Throw.isBusinessException("商品售价必须小于99999999元");
            }

            if (originPrice != null && originPrice.compareTo(BigDecimal.ZERO) > 0) {
                if (originPrice.compareTo(new BigDecimal("99999999")) > 0) {
                    Throw.isBusinessException("划线价格必须小于99999999元");
                }

                if (originPrice.compareTo(goodsPrice) < 0) {
                    Throw.isBusinessException("划线价格必须大于等于商品售价");
                }
            }

            if (totalStock == null || totalStock <= 0) {
                Throw.isBusinessException("库存必须大于0件");
            }

            if (totalStock > 99999999) {
                Throw.isBusinessException("库存必须大于小于99999999件");
            }

            // 核销方式（只对报名活动有效）：0-系统，1-票付通
            Integer verifyType = goodsReleaseDto.getVerifyType();
            if (VerifyTypeEnum.TYF.getValue().equals(verifyType)) {
                String pftProduct = goodsReleaseDto.getPftProduct();
                if (StringUtils.isBlank(pftProduct)) {
                    Throw.isBusinessException("请输入票付通产品ID");
                }

                if (pftProduct.length() > 50) {
                    Throw.isBusinessException("票付通产品ID最多输入50个字");
                }

                String pftTicket = goodsReleaseDto.getPftTicket();
                if (StringUtils.isBlank(pftTicket)) {
                    Throw.isBusinessException("请输入票付通门票ID");
                }

                if (pftTicket.length() > 50) {
                    Throw.isBusinessException("票付通门票ID最多输入50个字");
                }

                String pftSupplier = goodsReleaseDto.getPftSupplier();
                if (StringUtils.isBlank(pftSupplier)) {
                    Throw.isBusinessException("请输入票付通供应商ID");
                }

                if (pftSupplier.length() > 50) {
                    Throw.isBusinessException("票付通供应商ID最多输入50个字");
                }

                boolean flag = orderApi.pftOrderPreCheck(pftSupplier
                        , pftProduct, pftTicket).unpack();
                if (!flag) {
                    Throw.isBusinessException("票付通参数设置有误，请确认后重试");
                }
            }
        }

        TbGoodsPo tbGoodsPo = new TbGoodsPo();
        BeanUtils.copyProperties(goodsReleaseDto, tbGoodsPo);
        tbGoodsPo.setRemainStock(goodsReleaseDto.getTotalStock());
        tbGoodsPo.setSaleCount(0);
        tbGoodsPo.setCreateTime(LocalDateTime.now());
        tbGoodsPo.setUpdateTime(LocalDateTime.now());

        if (GoodsStateEnum.ON.getValue().equals(goodsState)) {
            tbGoodsPo.setUpTime(LocalDateTime.now());
        }

        int insert = baseMapper.insert(tbGoodsPo);
        if (insert == 0) {
            Throw.isBusinessException("发布商品失败");
        }

        return insert;
    }

    @Override
    public Integer offGoods(GoodsOffDto goodsOffDto) {
        List<Long> ids = goodsOffDto.getIds();
        if (CollectionUtils.isEmpty(ids)) {
            Throw.isBusinessException("请选择下架的商品");
        }

        List<TbGoodsPo> tbGoodsPos = baseMapper.selectList(new QueryWrapper<TbGoodsPo>().eq("del_state", 0)
                .eq(goodsOffDto.getMerchantId() != null, "merchant_id", goodsOffDto.getMerchantId())
                .eq(goodsOffDto.getBusinessMerchantId() != null, "business_merchant_id", goodsOffDto.getBusinessMerchantId())
                .in("id", ids));
        if (CollectionUtils.isEmpty(tbGoodsPos)) {
            Throw.isBusinessException("请选择下架的商品");
        }

        LocalDateTime now = LocalDateTime.now();
        List<Long> goodsIds = tbGoodsPos.stream().map(TbGoodsPo::getId).collect(Collectors.toList());
        // 当前商品有关联活动，关联的活动有效期未过，不能下架(当前时间不晚于活动有效结束时间，不可以下架)
        List<TbActiveGoodsStockPo> activeGoodsStockPos = activeGoodsStockMapper.listRelActiveByGoodsIds(goodsIds, now);
        if (!CollectionUtils.isEmpty(activeGoodsStockPos)) {
            Throw.isBusinessException("商品正在参与活动不能下架");
        }

        for (TbGoodsPo tbGoodsPo : tbGoodsPos) {
            if (GoodsStateEnum.OFF.getValue().equals(tbGoodsPo.getGoodsState())) {
                continue;
            }

            tbGoodsPo.setGoodsState(GoodsStateEnum.OFF.getValue());
            tbGoodsPo.setOffTime(now);
            tbGoodsPo.setUpdateTime(now);
            baseMapper.offGoods(tbGoodsPo);
        }

        return 1;
    }

    @Override
    public Integer batchOnGoods(GoodsOnDto goodsOnDto) {
        List<Long> ids = goodsOnDto.getIds();
        if (CollectionUtils.isEmpty(ids)) {
            Throw.isBusinessException("请选择上架的商品");
        }

        List<TbGoodsPo> tbGoodsPos = baseMapper.selectList(new QueryWrapper<TbGoodsPo>().eq("del_state", 0)
                .eq(goodsOnDto.getMerchantId() != null, "merchant_id", goodsOnDto.getMerchantId())
                .eq(goodsOnDto.getBusinessMerchantId() != null, "business_merchant_id", goodsOnDto.getBusinessMerchantId())
                .in("id", ids));
        if (CollectionUtils.isEmpty(tbGoodsPos)) {
            Throw.isBusinessException("请选择上架的商品");
        }

        for (TbGoodsPo tbGoodsPo : tbGoodsPos) {
            if (GoodsStateEnum.ON.getValue().equals(tbGoodsPo.getGoodsState())) {
                continue;
            }

            tbGoodsPo.setGoodsState(GoodsStateEnum.ON.getValue());
            tbGoodsPo.setUpTime(LocalDateTime.now());
            tbGoodsPo.setUpdateTime(LocalDateTime.now());
            baseMapper.onGoods(tbGoodsPo);
        }

        return 1;
    }

    @Override
    public Integer onGoods(GoodsOnDto goodsOnDto) {
        TbGoodsPo tbGoodsPo = baseMapper.selectById(goodsOnDto.getId());
        if (tbGoodsPo == null || tbGoodsPo.getDelState() == 1) {
            Throw.isBusinessException("商品不存在");
        }

        if (goodsOnDto.getMerchantId() != null && !tbGoodsPo.getMerchantId().equals(goodsOnDto.getMerchantId())) {
            Throw.isBusinessException("商品不存在");
        }

        if (goodsOnDto.getBusinessMerchantId() != null && !tbGoodsPo.getBusinessMerchantId().equals(goodsOnDto.getBusinessMerchantId())) {
            Throw.isBusinessException("商品不存在");
        }

        if (GoodsStateEnum.ON.getValue().equals(tbGoodsPo.getGoodsState())) {
            return 0;
        }

        tbGoodsPo.setGoodsState(GoodsStateEnum.ON.getValue());
        tbGoodsPo.setUpTime(LocalDateTime.now());
        tbGoodsPo.setUpdateTime(LocalDateTime.now());
        int update = baseMapper.onGoods(tbGoodsPo);
        if (update == 0) {
            Throw.isBusinessException("上架商品失败");
        }

        return update;
    }

    @Override
    public Integer updateGoodsStock(GoodsStockUpdateDto goodsStockUpdateDto) {
        TbGoodsPo tbGoodsPo = baseMapper.selectById(goodsStockUpdateDto.getId());
        if (tbGoodsPo == null || tbGoodsPo.getDelState() == 1) {
            Throw.isBusinessException("商品不存在");
        }

        if (goodsStockUpdateDto.getMerchantId() != null && !tbGoodsPo.getMerchantId().equals(goodsStockUpdateDto.getMerchantId())) {
            Throw.isBusinessException("商品不存在");
        }

        if (goodsStockUpdateDto.getBusinessMerchantId() != null && !tbGoodsPo.getBusinessMerchantId().equals(goodsStockUpdateDto.getBusinessMerchantId())) {
            Throw.isBusinessException("商品不存在");
        }

        // 如果是上架状态，则不能改库存
        if (GoodsStateEnum.ON.getValue().equals(tbGoodsPo.getGoodsState())) {
            Throw.isBusinessException("已上架的商品不能改库存");
        }

        LocalDateTime now = LocalDateTime.now();
        // 当前商品有关联活动，关联的活动有效期未过，不可改库存(当前时间不晚于活动有效结束时间，不可改库存)
        List<TbActiveGoodsStockPo> activeGoodsStockPos = activeGoodsStockMapper.listRelActiveByGoodsIds(Collections.singletonList(tbGoodsPo.getId()), now);
        if (!CollectionUtils.isEmpty(activeGoodsStockPos)) {
            Throw.isBusinessException("商品正在参与活动不能改库存");
        }

        // 计算剩余库存=修改后的库存-冻结库存
        int remainStock = goodsStockUpdateDto.getTotalStock();
        List<TbActiveGoodsStockPo> activeGoodsStockPoList = activeGoodsStockMapper.selectList(new QueryWrapper<TbActiveGoodsStockPo>().eq("del_state", 0)
                .eq("goods_id", tbGoodsPo.getId()));
        if (!CollectionUtils.isEmpty(activeGoodsStockPoList)) {
            int sum = activeGoodsStockPoList.stream().mapToInt(TbActiveGoodsStockPo::getFreezeStock).sum();
            // 校验，修改之后的库存不能低于当前冻结的库存
            if (goodsStockUpdateDto.getTotalStock() <= sum) {
                Throw.isBusinessException("修改之后的库存不能低于当前冻结的库存");
            }
            remainStock = goodsStockUpdateDto.getTotalStock() - sum;
        }

        tbGoodsPo.setTotalStock(goodsStockUpdateDto.getTotalStock());
        tbGoodsPo.setRemainStock(remainStock);
        tbGoodsPo.setUpdateTime(now);
        int update = baseMapper.updateById(tbGoodsPo);
        if (update == 0) {
            Throw.isBusinessException("改库存失败");
        }

        return update;
    }

    @Override
    public Integer updateGoodsPrice(GoodsPriceUpdateDto goodsPriceUpdateDto) {
        TbGoodsPo tbGoodsPo = baseMapper.selectById(goodsPriceUpdateDto.getId());
        if (tbGoodsPo == null || tbGoodsPo.getDelState() == 1) {
            Throw.isBusinessException("商品不存在");
        }

        if (goodsPriceUpdateDto.getMerchantId() != null && !tbGoodsPo.getMerchantId().equals(goodsPriceUpdateDto.getMerchantId())) {
            Throw.isBusinessException("商品不存在");
        }

        if (goodsPriceUpdateDto.getBusinessMerchantId() != null && !tbGoodsPo.getBusinessMerchantId().equals(goodsPriceUpdateDto.getBusinessMerchantId())) {
            Throw.isBusinessException("商品不存在");
        }

        // 如果是上架状态，则不能改价格
        if (GoodsStateEnum.ON.getValue().equals(tbGoodsPo.getGoodsState())) {
            Throw.isBusinessException("已上架的商品不能改价格");
        }

        LocalDateTime now = LocalDateTime.now();
        // 当前商品有关联活动，关联的活动有效期未过，不可改价(当前时间不晚于活动有效结束时间，不可改价)
        List<TbActiveGoodsStockPo> activeGoodsStockPos = activeGoodsStockMapper.listRelActiveByGoodsIds(Collections.singletonList(tbGoodsPo.getId()), now);
        if (!CollectionUtils.isEmpty(activeGoodsStockPos)) {
            Throw.isBusinessException("商品正在参与活动不能改价格");
        }

        tbGoodsPo.setGoodsPrice(goodsPriceUpdateDto.getGoodsPrice());
        tbGoodsPo.setUpdateTime(LocalDateTime.now());
        int update = baseMapper.updateById(tbGoodsPo);
        if (update == 0) {
            Throw.isBusinessException("改价失败");
        }

        return update;
    }

    @Override
    public Integer updateGoods(GoodsUpdateDto goodsUpdateDto) {
        Integer goodsState = goodsUpdateDto.getGoodsState();
        String goodsName = goodsUpdateDto.getGoodsName();
        BigDecimal goodsPrice = goodsUpdateDto.getGoodsPrice();
        BigDecimal originPrice = goodsUpdateDto.getOriginPrice();
        Integer totalStock = goodsUpdateDto.getTotalStock();

        if (!GoodsStateEnum.WAIT.getValue().equals(goodsState)) {
            if (StringUtils.isBlank(goodsName)) {
                Throw.isBusinessException("请输入商品标题");
            }

            if (goodsName.length() > 50) {
                Throw.isBusinessException("商品标题最多输入50个字");
            }

            if (goodsPrice == null || goodsPrice.compareTo(BigDecimal.ZERO) <= 0) {
                goodsUpdateDto.setGoodsPrice(BigDecimal.ZERO);
//                Throw.isBusinessException("商品售价必须大于0元");
            }

            if (goodsPrice.compareTo(new BigDecimal("99999999")) > 0) {
                Throw.isBusinessException("商品售价必须小于99999999元");
            }

            if (originPrice != null && originPrice.compareTo(BigDecimal.ZERO) > 0) {
                if (originPrice.compareTo(new BigDecimal("99999999")) > 0) {
                    Throw.isBusinessException("划线价格必须小于99999999元");
                }

                if (originPrice.compareTo(goodsPrice) < 0) {
                    Throw.isBusinessException("划线价格必须大于等于商品售价");
                }
            }

            if (totalStock == null || totalStock <= 0) {
                Throw.isBusinessException("库存必须大于0件");
            }

            if (totalStock > 99999999) {
                Throw.isBusinessException("库存必须大于小于99999999件");
            }

            // 核销方式（只对报名活动有效）：0-系统，1-票付通
            Integer verifyType = goodsUpdateDto.getVerifyType();
            if (VerifyTypeEnum.TYF.getValue().equals(verifyType)) {
                String pftProduct = goodsUpdateDto.getPftProduct();
                if (StringUtils.isBlank(pftProduct)) {
                    Throw.isBusinessException("请输入票付通产品ID");
                }

                if (pftProduct.length() > 50) {
                    Throw.isBusinessException("票付通产品ID最多输入50个字");
                }

                String pftTicket = goodsUpdateDto.getPftTicket();
                if (StringUtils.isBlank(pftTicket)) {
                    Throw.isBusinessException("请输入票付通门票ID");
                }

                if (pftTicket.length() > 50) {
                    Throw.isBusinessException("票付通门票ID最多输入50个字");
                }

                String pftSupplier = goodsUpdateDto.getPftSupplier();
                if (StringUtils.isBlank(pftSupplier)) {
                    Throw.isBusinessException("请输入票付通供应商ID");
                }

                if (pftSupplier.length() > 50) {
                    Throw.isBusinessException("票付通供应商ID最多输入50个字");
                }

                boolean flag = orderApi.pftOrderPreCheck(pftSupplier
                        , pftProduct, pftTicket).unpack();
                if (!flag) {
                    Throw.isBusinessException("票付通参数设置有误，请确认后重试");
                }
            }
        }

        TbGoodsPo tbGoodsPo = baseMapper.selectById(goodsUpdateDto.getId());
        if (tbGoodsPo == null || tbGoodsPo.getDelState() != 0) {
            Throw.isBusinessException("商品不存在");
        }

        // 商家商户可以修改商品归属商家
//        if (goodsUpdateDto.getMerchantId() != null && !tbGoodsPo.getMerchantId().equals(goodsUpdateDto.getMerchantId())) {
//            Throw.isBusinessException("商品不存在");
//        }

        if (tbGoodsPo.getBusinessMerchantId() != null) {
             if (!tbGoodsPo.getBusinessMerchantId().equals(goodsUpdateDto.getBusinessMerchantId())) {
                 Throw.isBusinessException("商品不存在");
             }
        } else {
            goodsUpdateDto.setBusinessMerchantId(null);
        }

        if (GoodsStateEnum.ON.getValue().equals(tbGoodsPo.getGoodsState())) {
            Throw.isBusinessException("已上架的商品不能编辑");
        }

        LocalDateTime now = LocalDateTime.now();
        // 当前商品有关联活动，关联的活动有效期未过，不可编辑(当前时间不晚于活动有效结束时间，不可编辑)
        List<TbActiveGoodsStockPo> activeGoodsStockPos = activeGoodsStockMapper.listRelActiveByGoodsIds(Collections.singletonList(tbGoodsPo.getId()), now);
        if (!CollectionUtils.isEmpty(activeGoodsStockPos)) {
            Throw.isBusinessException("商品正在参与活动不能编辑");
        }

        // 计算剩余库存=修改后的库存-冻结库存
        int remainStock = totalStock;
        if (!CollectionUtils.isEmpty(activeGoodsStockPos)) {
            int sum = activeGoodsStockPos.stream().mapToInt(TbActiveGoodsStockPo::getFreezeStock).sum();
            // 校验，修改之后的库存不能低于当前冻结的库存
            if (totalStock <= sum) {
                Throw.isBusinessException("修改之后的库存不能低于当前冻结的库存");
            }
            remainStock = totalStock - sum;
        }

        BeanUtils.copyProperties(goodsUpdateDto, tbGoodsPo);
        tbGoodsPo.setTotalStock(totalStock);
        tbGoodsPo.setRemainStock(remainStock);
        tbGoodsPo.setUpdateTime(now);
        int update = baseMapper.updateById(tbGoodsPo);
        if (update == 0) {
            Throw.isBusinessException("编辑商品失败");
        }

        return update;
    }

    @Override
    public Integer deleteGoods(Long id, Long merchantId) {
        TbGoodsPo tbGoodsPo = baseMapper.selectById(id);
        if (tbGoodsPo == null || tbGoodsPo.getDelState() != 0 || !tbGoodsPo.getMerchantId().equals(merchantId)) {
            Throw.isBusinessException("商品不存在");
        }

        if (GoodsStateEnum.ON.getValue().equals(tbGoodsPo.getGoodsState())) {
            Throw.isBusinessException("已上架的商品不能删除");
        }

        LocalDateTime now = LocalDateTime.now();
        // 当前商品有关联活动，关联的活动有效期未过，不可删除(当前时间不晚于活动有效结束时间，不可删除)
        List<TbActiveGoodsStockPo> activeGoodsStockPos = activeGoodsStockMapper.listRelActiveByGoodsIds(Collections.singletonList(tbGoodsPo.getId()), now);
        if (!CollectionUtils.isEmpty(activeGoodsStockPos)) {
            Throw.isBusinessException("商品正在参与活动不能删除");
        }

        tbGoodsPo.setDelState(1);
        tbGoodsPo.setUpdateTime(LocalDateTime.now());
        int update = baseMapper.updateById(tbGoodsPo);
        if (update == 0) {
            Throw.isBusinessException("删除商品失败");
        }

        return update;
    }

    @Override
    public Integer deleteBusinessMerchantGoods(Long id, Long businessMerchantId) {
        TbGoodsPo tbGoodsPo = baseMapper.selectById(id);
        if (tbGoodsPo == null || tbGoodsPo.getDelState() != 0 || !tbGoodsPo.getBusinessMerchantId().equals(businessMerchantId)) {
            Throw.isBusinessException("商品不存在");
        }

        if (GoodsStateEnum.ON.getValue().equals(tbGoodsPo.getGoodsState())) {
            Throw.isBusinessException("已上架的商品不能删除");
        }

        LocalDateTime now = LocalDateTime.now();
        // 当前商品有关联活动，关联的活动有效期未过，不可删除(当前时间不晚于活动有效结束时间，不可删除)
        List<TbActiveGoodsStockPo> activeGoodsStockPos = activeGoodsStockMapper.listRelActiveByGoodsIds(Collections.singletonList(tbGoodsPo.getId()), now);
        if (!CollectionUtils.isEmpty(activeGoodsStockPos)) {
            Throw.isBusinessException("商品正在参与活动不能删除");
        }

        tbGoodsPo.setDelState(1);
        tbGoodsPo.setUpdateTime(LocalDateTime.now());
        int update = baseMapper.updateById(tbGoodsPo);
        if (update == 0) {
            Throw.isBusinessException("删除商品失败");
        }

        return update;
    }

    @Override
    public Integer batchDeleteGoods(GoodsDelDto goodsDelDto) {
        List<Long> ids = goodsDelDto.getIds();
        if (CollectionUtils.isEmpty(ids)) {
            Throw.isBusinessException("请选择删除的商品");
        }

        List<TbGoodsPo> tbGoodsPos = baseMapper.selectList(new QueryWrapper<TbGoodsPo>().eq("del_state", 0)
                .eq(goodsDelDto.getMerchantId() != null, "merchant_id", goodsDelDto.getMerchantId())
                .eq(goodsDelDto.getBusinessMerchantId() != null, "business_merchant_id", goodsDelDto.getBusinessMerchantId())
                .in("id", ids));
        if (CollectionUtils.isEmpty(tbGoodsPos)) {
            Throw.isBusinessException("请选择删除的商品");
        }

        List<Long> goodsIds = tbGoodsPos.stream().map(TbGoodsPo::getId).collect(Collectors.toList());

        Map<Long, List<TbActiveGoodsStockPo>> activeGoodsStockPoMap = new HashMap<>();
        LocalDateTime now = LocalDateTime.now();
        List<TbActiveGoodsStockPo> activeGoodsStockPos = activeGoodsStockMapper.listRelActiveByGoodsIds(goodsIds, now);
        if (!CollectionUtils.isEmpty(activeGoodsStockPos)) {
            activeGoodsStockPoMap = activeGoodsStockPos.stream().collect(Collectors.groupingBy(TbActiveGoodsStockPo::getGoodsId));
        }

        // 校验商品是否可以被删除
        for (TbGoodsPo tbGoodsPo : tbGoodsPos) {
            if (GoodsStateEnum.ON.getValue().equals(tbGoodsPo.getGoodsState())) {
                Throw.isBusinessException("已上架的商品【" + tbGoodsPo.getGoodsName() + "】不能删除");
            }

            // 当前商品有关联活动，关联的活动有效期未过，不可删除(当前时间不晚于活动有效结束时间，不可删除)
            List<TbActiveGoodsStockPo> activeGoodsStockPoList = activeGoodsStockPoMap.get(tbGoodsPo.getId());
            if (!CollectionUtils.isEmpty(activeGoodsStockPoList)) {
                Throw.isBusinessException("商品【" + tbGoodsPo.getGoodsName() + "】正在参与活动不能删除");
            }
        }

        for (TbGoodsPo tbGoodsPo : tbGoodsPos) {
            tbGoodsPo.setDelState(1);
            tbGoodsPo.setUpdateTime(LocalDateTime.now());
            baseMapper.updateById(tbGoodsPo);
        }

        return 1;
    }

    @Override
    public Page<GoodsActivePageVo> pageGoodsActive(GoodsActivePageDto goodsActivePageDto) {
        PageHelper.startPage(goodsActivePageDto.getPageNum(), goodsActivePageDto.getPageSize());
        List<GoodsActivePageVo> goodsActivePageVos = baseMapper.listGoodsActiveByDto(goodsActivePageDto);
        PageInfo<GoodsActivePageVo> pageInfo = new PageInfo<>(goodsActivePageVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    @Override
    public Integer onGoodsCount(Long merchantId) {
        return baseMapper.selectCount(new QueryWrapper<TbGoodsPo>().eq("del_state", 0)
                .eq("merchant_id", merchantId).eq("goods_state", GoodsStateEnum.ON.getValue()));
    }

    @Override
    public List<GoodsCountVo> getGoodsCount(Long merchantId) {
        List<TbGoodsPo> tbGoodsPos = baseMapper.selectList(new QueryWrapper<TbGoodsPo>().eq("del_state", 0)
                .eq("merchant_id", merchantId));
        List<TbGoodsPo> collect = tbGoodsPos.stream().filter(e -> {
            // 过滤状态=非上架，策划人发布的商品
            if (!Objects.equals(e.getGoodsState(), GoodsStateEnum.ON.getValue()) && e.getBusinessMerchantId() != null) {
                return false;
            }
            return true;
        }).collect(Collectors.toList());
        return convertToGoodsCountList(collect);
    }

    @Override
    public List<GoodsCountVo> getBusinessMerchantGoodsCount(Long merchantId) {
        // 校验商户是否商家自有商户
        MerchantVo merchantVo = merchantApi.getById(merchantId).unpack();
        if (!OwnStateEnum.YES.getValue().equals(merchantVo.getOwnState())) {
            Throw.isBusinessException("暂无权限");
        }

        LambdaQueryWrapper<TbGoodsPo> qw = Wrappers.<TbGoodsPo>lambdaQuery()
                .eq(TbGoodsPo::getDelState, DeleteStatusEnum.NORMAL.getValue())
                .eq(TbGoodsPo::getBusinessMerchantId, merchantId);
        List<TbGoodsPo> tbGoodsPos = baseMapper.selectList(qw);

        return convertToGoodsCountList(tbGoodsPos);
    }

    private List<GoodsCountVo> convertToGoodsCountList(List<TbGoodsPo> tbGoodsPos) {
        if (CollectionUtils.isEmpty(tbGoodsPos)) {
            return Collections.emptyList();
        }

        Map<Integer, List<TbGoodsPo>> tbGoodsPoMap = tbGoodsPos.stream()
                .collect(Collectors.groupingBy(TbGoodsPo::getGoodsState));
        List<GoodsCountVo> goodsCountVos = new ArrayList<>();
        for (GoodsStateEnum goodsStateEnum : GoodsStateEnum.values()) {
            Integer goodsState = goodsStateEnum.getValue();
            List<TbGoodsPo> tbGoodsPoList = tbGoodsPoMap.get(goodsState);

            GoodsCountVo goodsCountVo = new GoodsCountVo();
            goodsCountVo.setGoodsState(goodsState);
            goodsCountVo.setNum(CollectionUtils.isEmpty(tbGoodsPoList) ? 0 : tbGoodsPoList.size());
            goodsCountVos.add(goodsCountVo);
        }
        return goodsCountVos;
    }

    @Override
    public Boolean scanOnGoodsStock() {
        List<TbGoodsPo> tbGoodsPos = baseMapper.selectList(new QueryWrapper<TbGoodsPo>().eq("del_state", 0)
                .eq("goods_state", GoodsStateEnum.ON.getValue())
                .lt("remain_stock", 5));
        if (CollectionUtils.isEmpty(tbGoodsPos)) {
            return true;
        }

        for (TbGoodsPo tbGoodsPo : tbGoodsPos) {
            // 发送库存预警系统通知
            NotifyMsgSendDto notifyMsgSendDto = new NotifyMsgSendDto();
            notifyMsgSendDto.setUserId(tbGoodsPo.getMerchantId());
            notifyMsgSendDto.setRoleType(RoleTypeEnum.MERCHANT.getValue());
            notifyMsgSendDto.setMsgType(NotifyMsgTypeEnum.MERCHANT_STOCK_WARN.getValue());
            notifyMsgSendDto.setContent(String.format(MsgConstant.MERCHANT_STOCK_WARN, tbGoodsPo.getGoodsName()));
            notifyMsgSendDto.setMsgState(NotifyMsgStateEnum.NO_READ.getValue());
            notifyMsgProvider.sendMsg(notifyMsgSendDto);
        }

        return true;
    }
}
